<?php

namespace app\admin\controller;

//引入Expedia酒店
use app\api\controller\ExpediaApi;
use app\api\controller\KbxOrder;
use think\Exception;
use think\Request;
use think\db;

class Expediacity extends User
{
    //20210428 定制系统国家页面支持 原方法 admin/poi/index
    public function country()
    {
        return $this->fetch();
    }

    //定制系统的国家 城市数据
    public function getCountryData()
    {
        $citys = db('city c')
            ->join('continent co', 'c.continentid=co.id', 'left')
            ->field('c.*,c.groupid as pid,co.name as continent_name,co.eng_name as continent_eng_name')
            ->order("pid asc,sort_weight desc")->select();

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => $citys,
            'count' => count($citys)
        ]);
    }
    ####################### 以下方式为支持expedia city ###################
    //获取expedia的大洲 国家 城市
    public function cityList()
    {
        //获取大洲数据
        $continents = (new KbxOrder())->listEContinents();
        $countries = (new ExpediaApi())->getExpediaCountryDataV2();
        $continents = !empty($continents['msg']) && is_array($continents['msg'])
            ? $continents['msg'] : [];
        $boundContinentEids = db('continent')->column('eId');
        foreach ($continents as $key=>$value){
            $continents[$key]['isBound'] = in_array($value['eId'],$boundContinentEids);
        }
        $this->assign(compact('continents', 'countries'));
        return $this->fetch();
    }

    //根据大洲获取国家
    public function getCountryByContinentId(Request $request)
    {
        if (!$request->isPost()) return $this->error('请以POST提交');
        $eId = $request->post('eId', '');
        if(empty($eId)){
            $data = (new ExpediaApi())->getExpediaCountryDataV2();
        }else{
            $result = (new KbxOrder())->listECountrys($eId);
            if (!empty($result['msg']) && is_array($result['msg'])) {
                $data = [];
                foreach ($result['msg'] as $value){
                    $data[] = (new ExpediaApi())->getSimpleData($eId,$value);
                }
            }
        }

        return $this->success('获取成功', '', $data);
    }

    //关联国家下的城市列表
    public function getCityByCountryId(Request $request)
    {
        $eId = $request->param('eId', '');
        $page = $request->param('page', 1);
        $limit = $request->param('limit', 50);
        if(empty($eId)) return $this->error('请选择国家');
        $result = (new KbxOrder())->listCityByCountry($eId,$page,$limit);
        if (!empty($result['msg']) && is_array($result['msg'])) {
            $data = [];
            $boundCityEids = db('city')->where(['type'=>'CITY'])->column('eId');
            foreach ($result['msg']['cities'] as $value){
                $cityOne = (new ExpediaApi())->getSimpleData($eId,$value);
                $cityOne['isBound'] = in_array($cityOne['eId'],$boundCityEids);
                $data[] = $cityOne;
            }
            $data = [
                'code'=>0,
                'msg'=>'success',
                'count'=>$result['msg']['total'] ?? ($result['msg']['totalPage'] * $limit),
                'data'=>$data
            ];
        }

        return json($data);
    }

    //expedia城市详情
    public function expediaCityInfo(Request $request)
    {
        $eId = $request->param('eId', '');
        if(empty($eId)) return $this->error('请选择城市');
        $city = (new KbxOrder())->getERegionByEId($eId)['msg'] ?? [];
        if(empty($city) || !is_array($city)) return $this->error('未查询到相关城市');

        $isBound = db('city')->where(['eId'=>$eId])->find();
        $city['boundCityId'] = !empty($isBound['id'])?$isBound['id']:0;
        //找到对应的国家ID
        $city['eCountry'] = (new ExpediaApi())->findAncestorsCountry($city);
        $this->assign(compact('city'));
        return $this->fetch();
    }

    //批量导入POI
    public function batchImportPoiByCityId(Request $request)
    {
        //根据标题 存在则关联不存在则创建
        $cityId = $request->param('cityId', '');
        if(empty($cityId)) return $this->error('缺少城市ID');
        $city = db('city')->find($cityId);
        if(empty($city)) return $this->error('未查询到相关城市');

        $poidata = $request->param('poidata', '');
        if(empty($poidata)) return $this->error('请选择需要导入的ID');
        $poidata = json_decode($poidata,true);
        //遍历循环数据
        //获取当前城市下的所有POI
        $poiTable = db('poi')->field('id,name,eng_name,eId')
            ->where(['groupid'=>$cityId,'typeid'=>1,'eng_name'=>['neq','']])->select();
        $poiTableEnNames = [];
        foreach ($poiTable as $key=>$value){
            $poiTableEnNames[$key] = strtolower($value['eng_name']);
        }
        //查找到需要更新和插入的内容
        $insertData = [];
        $updData = [];
        foreach ($poidata as $key=>$value){
            if(empty($value['nameEn'])) continue;
            //根据英文名进行匹配
            $index = array_search(strtolower($value['nameEn']),$poiTableEnNames);
            //不存在则如新增库
            if($index===false){
                $insertData[] = $this->filterPoiData($cityId,$value);
            }elseif(empty($poiTable['index']['eId'])){//已存在eId的数据直接忽略
                $poi_id = $poiTable[$index]['id'];
                if(empty($poi_id)) continue;
                $updData[] = [
                    'poi_id'=>$poi_id,
                    'eId'=>$value['eId']
                ];
            }

        }
        try{
            if(!empty($updData)){
                foreach ($updData as $key=>$value){
                    db('poi')->where(['id'=>$value['poi_id']])->update([
                        'eId'=>$value['eId'],
                        'update_time'=>time()
                    ]);
                }
            }
            if(!empty($insertData)){
                db('poi')->insertAll($insertData);
            }
            trace('获取数据库POI共'.count($poiTable).'条，需要导入的数据共'.count($poidata).'条');
            trace('匹配要更新的数据'.count($updData).'条，要插入的数据'.count($insertData).'条');
            db::commit();
            return $this->success('导入成功');
        }catch (Exception $e){
            db::rollback();
            return $this->error($e->getMessage());
        }

    }

    protected function filterPoiData($cityId,$value)
    {
        return [
            'name'=>$value['name'],
            'eng_name'=>$value['nameEn'],
            'typeid'=>1,
            'groupid'=>$cityId,
            'lat'=>$value['coordinates']['center_latitude']??'',
            'lng'=>$value['coordinates']['center_longitude']??'',
            'address'=>$value['name_full']??'',
            'create_time'=>time(),
            'update_time'=>time(),
            'eId'=>$value['eId'],
        ];

    }


}
